#include "head.h"

int server_ls(int net_fd, char *cur_path)
{
    DIR * dirp = opendir(cur_path);
    // 打开目录流需要进行错误处理
    ERROR_CHECK(dirp,NULL,"opendir");
    struct dirent * pdirent;

    char file_list[4096] = {0};
    // 循环读目录项并打印目录信息，循环结束的条件是返回值为NULL   
    while((pdirent = readdir(dirp)) != NULL)
    {
        if (strcmp(pdirent->d_name, ".") != 0 && strcmp(pdirent->d_name, "..") != 0)
        {
            // 拼接文件名和两个空格
            strcat(file_list, pdirent->d_name);
            strcat(file_list, "  ");  // 两个空格间隔
        }

    }

    int res = send(net_fd, file_list, sizeof(file_list), MSG_NOSIGNAL);
    // 及时释放资源，关闭目录流
    if(res==-1)
    {
        printf("the client is disconnected\n");
        closedir(dirp);
        return -1;
    }
    closedir(dirp);
    return 0;
}
